package com.dqy.twserver.server.handle.ehandle;

import com.dqy.twserver.server.dto.GameDto;
import com.dqy.twserver.server.support.Player;
import com.dqy.twserver.server.support.SupportMap;
import com.dqy.twserver.server.support.data.RoomInfo;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class GameEventCreateRoomHandle implements  GameEventHandle{
    static AtomicInteger atomicInteger=new AtomicInteger(0);
    static Logger logger = LoggerFactory.getLogger(GameEventCreateRoomHandle.class);
    @Override
    public void handle(GameDto req, NioSocketChannel channel) throws Exception {
        int rid=atomicInteger.incrementAndGet();

        logger.info("[GameEventCreateRoomHandle] start");
        Map<Integer, RoomInfo> roomMap = SupportMap.roomMap;
        String playerName = req.getPlayerName();
        String roomName = req.getInfo();
        GameDto resp=new GameDto();

        String errMsg = checkRoom(roomName,playerName);
        if(errMsg!=null){
            resp.setSts(400);
            resp.setInfo(errMsg);
            channel.writeAndFlush(resp);
            return;
        }

        String roomId="RID#"+rid;
        RoomInfo roomInfo=new RoomInfo(roomId,roomName, playerName);
        roomInfo.setPlayerList(new ArrayList<>());
        roomInfo.setRoomSts("0"); //设置房间状态为为准备
        roomInfo.setRoomCreateUser(playerName);
        roomInfo.getPlayerList().add(SupportMap.playerMap.get(playerName)); //添加房间默认人数
        roomMap.put(rid,roomInfo);

        SupportMap.playerMap.get(playerName).setRoomId(rid);

        resp.setSts(200);
        resp.setRoomId(roomId);
        resp.setInfo("创建房间成功");
        channel.writeAndFlush(resp);

        logger.info("[GameEventCreateRoomHandle] end");
    }

    private String checkRoom(String roomName,String uname){
        String errMsg=null;
        Map<Integer, RoomInfo> roomMap = SupportMap.roomMap;
        Player playConnect = SupportMap.playerMap.get(uname);

        for(Integer key: roomMap.keySet()){
            RoomInfo roomInfo = roomMap.get(key);
            if(roomName.equals(roomInfo.getRoomName())){
                errMsg="已存在名字相同的房间，请另外使用一个名字";
                break;
            }
            if(uname.equals(roomInfo.getRoomCreateUser())) {
                errMsg="你不能创建多个房间";
                break;
            }
            if(roomInfo.getPlayerList().contains(playConnect)){
                errMsg="你已经在一个房间中，请先退出当前房间！（" + roomInfo.getRoomName() +")";
                break;
            }
        }
        return errMsg;
    }
}
